package cn.iutils.signin.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.iutils.common.Page;
import cn.iutils.common.utils.JStringUtils;
import cn.iutils.common.controller.BaseController;
import cn.iutils.signin.entity.Signin;
import cn.iutils.signin.service.SigninService;

import javax.servlet.http.HttpServletRequest;

/**
* 签到 控制器
* @author iutils.cn
* @version 1.0
*/
@Controller
@RequestMapping("${adminPath}/signin")
public class SigninController extends BaseController {

    @Autowired
    private SigninService signinService;

    @ModelAttribute
    public Signin get(@RequestParam(required = false) String id) {
        Signin entity = null;
        if (JStringUtils.isNotBlank(id)) {
            entity = signinService.get(id);
        }
        if (entity == null) {
            entity = new Signin();
        }
        return entity;
    }

    /**
     * 签到记录
     * @param model
     * @param page
     * @return
     */
    @RequiresPermissions("signin:view")
    @RequestMapping()
    public String list(Model model, Page<Signin> page) {
        page.setOrderBy("a.create_date desc");
        model.addAttribute("page", page.setList(signinService.findPage(page)));
        return "signin/list";
    }

    /**
     * 签到
     * @param signin
     * @param request
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("signin:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(Signin signin, HttpServletRequest request,RedirectAttributes redirectAttributes) {
        signin.setIp(getRemoteAddr(request));
        signinService.save(signin);
        addMessage(redirectAttributes,"新增成功");
        return "redirect:"+ adminPath +"/signin/update?id="+signin.getId();
    }

    /**
     * 删除记录
     * @param id
     * @param pageNo
     * @param pageSize
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("signin:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable("id") String id,int pageNo,int pageSize, RedirectAttributes redirectAttributes) {
        signinService.delete(id);
        addMessage(redirectAttributes,"删除成功");
        return "redirect:"+ adminPath +"/signin?pageNo="+pageNo+"&pageSize="+pageSize;
    }
}
